<link rel="stylesheet" href="https://stripe.onliday.com/public/checkout.css" />
<!-- Display a payment form -->
<form id="payment-form">
  <div id="link-authentication-element">
    <!--Stripe.js injects the Link Authentication Element-->
  </div>
  <div id="payment-element">
    <!--Stripe.js injects the Payment Element-->
  </div>
  <button id="submit">
    <div class="spinner hidden" id="spinner"></div>
    <span id="button-text">Pay now</span>
  </button>
  <div id="payment-message" class="hidden"></div>
</form>

<script>
  $(function () {
    // // 禁止输入框输入
    // $(".control-all-search").each(function(){
    //   const input = $(this).find("input");
    //   if(input){
    //     input.attr('readonly', 'readonly')
    //   }
    // })
    // // 绑定点开事件
    // $(".control-all-search").click(function(event){
    //   // 阻止点击事件
    //   event.stopImmediatePropagation();
    //   event.preventDefault();
    // })
    // function createScript(URL, callback) {
    //   const currentScript = $("script[src='" + URL + "']");
    //   //是否存在；存在直接执行
    //   if (currentScript.length) {
    //     callback && callback();
    //     return;
    //   }
    //   const script = document.createElement("script");
    //   script.setAttribute("type", "text/javascript");
    //   script.setAttribute("src", URL);
    //   script.onload = function () {
    //     callback && callback();
    //   };
    //   script.onerror = function () { };
    //   document.body.appendChild(script);
    // }
    createScript("https://js.stripe.com/v3/", function () {

      const stripe = Stripe("pk_test_51Jh5neHUpSnFrFhkQ4zySOhP24xdQG3hwHJWwtoI2g8CulmPfecHYJ98SZw1ZPYmReQYbQPXW5m8ACRreJARv1n900FZmjQdnB");

      const items = [{ amount: "1700", currency: "USD", order_id: "2023081127817_1691996510" }];

      let elements;

      initialize();
      checkStatus();

      document.querySelector("#payment-form").addEventListener("submit", handleSubmit);

      let emailAddress = "";
      // Fetches a payment intent and captures the client secret
      async function initialize() {
        const { clientSecret } = await fetch("https://stripe.onliday.com/stripe/ck_info.php", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ items }),
        }).then((r) => r.json());

        elements = stripe.elements({ clientSecret });

        const linkAuthenticationElement = elements.create("linkAuthentication");
        linkAuthenticationElement.mount("#link-authentication-element");

        const paymentElementOptions = {
          layout: "tabs",
        };

        const paymentElement = elements.create("payment", paymentElementOptions);
        paymentElement.mount("#payment-element");
      }

      async function handleSubmit(e) {


        const { code } = window['oemPaymentVerification'] ? await oemPaymentVerification() : { code: 200 };
        if (code !== 200) {
          return false
        }

        e.preventDefault();
        setLoading(true);


        const { error } = await stripe.confirmPayment({
          elements,
          confirmParams: {
            // Make sure to change this to your payment completion page
            return_url: "https://stripe.onliday.com/stripe/ck_success.php?token=57f986c07af7a4d6ba303e3b022759f7",
            receipt_email: emailAddress,
          },
        });

        // This point will only be reached if there is an immediate error when
        // confirming the payment. Otherwise, your customer will be redirected to
        // your `return_url`. For some payment methods like iDEAL, your customer will
        // be redirected to an intermediate site first to authorize the payment, then
        // redirected to the `return_url`.
        if (error.type === "card_error" || error.type === "validation_error") {
          showMessage(error.message);
        } else {
          showMessage("An unexpected error occurred.");
        }

        setLoading(false);
      }

      // Fetches the payment intent status after payment submission
      async function checkStatus() {
        const clientSecret = new URLSearchParams(window.location.search).get(
          "payment_intent_client_secret"
        );

        if (!clientSecret) {
          return;
        }

        const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

        switch (paymentIntent.status) {
          case "succeeded":
            showMessage("Payment succeeded!");
            break;
          case "processing":
            showMessage("Your payment is processing.");
            break;
          case "requires_payment_method":
            showMessage("Your payment was not successful, please try again.");
            break;
          default:
            showMessage("Something went wrong.");
            break;
        }
      }

      // ------- UI helpers -------

      function showMessage(messageText) {
        const messageContainer = document.querySelector("#payment-message");

        messageContainer.classList.remove("hidden");
        messageContainer.textContent = messageText;

        setTimeout(function () {
          messageContainer.classList.add("hidden");
          messageContainer.textContent = "";
        }, 4000);
      }

      // Show a spinner on payment submission
      function setLoading(isLoading) {
        if (isLoading) {
          // Disable the button and show a spinner
          document.querySelector("#submit").disabled = true;
          document.querySelector("#spinner").classList.remove("hidden");
          document.querySelector("#button-text").classList.add("hidden");
        } else {
          document.querySelector("#submit").disabled = false;
          document.querySelector("#spinner").classList.add("hidden");
          document.querySelector("#button-text").classList.remove("hidden");
        }
      }
    })
  })



</script>